package tsif.tcluster;

import tsif.tcluster.service.TClusterService;
import tsif.tcluster.session.TClusterSession;

/**
 * 集群中央控制<br>
 * 1. 控制管理集群环境Id<br>
 * 2. 控制维护唯一服务Key<br>
 */
public abstract class TClusterMaster extends TClusterService {
	/** 中央管理服务环境Id **/
	public static final int MASTER_CONTEXT_ID = 0;
	/** 中央管理服务Id **/
	public static final long MASTER_SERVICE_ID = 1;
	/** 对方本地服务Id **/
	public static final long LOCAL_SERVICE_ID = 2;

	/**
	 * 绑定唯一服务, 如果存在唯一服务, 返回存在的服务Id.<br>
	 * 
	 * @param replace
	 *            是否替换服务Id
	 * @param serviceId
	 *            要绑定的服务Id
	 * 
	 * **/
	protected abstract long bindUniqueService(String key, long serviceId, boolean replace);

	/** 解除唯一服务Id的绑定 **/
	protected abstract void unbindUniqueService(String key, long serviceId);

	/** 获取全局唯一服务Id **/
	public abstract long getUniqueService(String key);

	/**
	 * 注册集群环境<br>
	 * 
	 * @param contextId
	 *            集群Id(0为自动分配, 可指定)
	 * **/
	protected abstract int registerContext(int contextId, String host, int port);

	/** 移除集群环境 **/
	protected abstract boolean removeContext(int contextId);

	/** 更新集群环境 **/
	protected abstract void updateContext(int contextId);

	/** 获取集群环境数据 **/
	public abstract ContextNode getContext(int contextId);

	/** 获取集群连接(依赖当前绑定的环境实现) **/
	protected TClusterSession getSession(int contextId) {
		return context.getSession(contextId);
	}

	/** 关闭停止当前所有集群环境 **/
	public void abort(int shutdownTime) {
		abort(shutdownTime, true);
	}

	/** 关闭停止当前所有集群环境 **/
	public abstract void abort(int shutdownTime, boolean shutdownSelf);

	/** 集群环境节点 **/
	public static class ContextNode {
		protected int id;
		protected String host;
		protected int port;
		protected long updateTime;

		public int getId() {
			return id;
		}

		public String getHost() {
			return host;
		}

		public int getPort() {
			return port;
		}

		public long getUpdateTime() {
			return updateTime;
		}

		public void setId(int id) {
			this.id = id;
		}

		public void setHost(String host) {
			this.host = host;
		}

		public void setPort(int port) {
			this.port = port;
		}

		public void setUpdateTime(long updateTime) {
			this.updateTime = updateTime;
		}

		@Override
		public String toString() {
			return "ContextNode [id=" + id + ", host=" + host + ", port=" + port + "]";
		}
	}

}
